var fs = require('fs')
var userPath = require('../config/pathConfig.js').userPath
var util = require('../utility/util.js')
var pageConfig = require('../config/pageConfig')

var fileName = 'users.data'

var safePathCheck = util.safePathCheck

var aPageCount = pageConfig.aPageCount

module.exports = {
    find: function(fliter, callback) {
        var page = fliter.page
        safePathCheck(userPath, fileName, function(exists) {
            if (exists) {
                var data = fs.readFileSync(userPath + fileName)
                data = JSON.parse(data)
            } else {
                var data = []
            }

            if (page) {
                data = data.slice((page - 1) * aPageCount, page * aPageCount)
            }

            callback(null, data)
        })
    },
    findByName: function(name, callback) {
        getData(function(err, users) {
            if (err) {
                callback(err)
                return
            }
            var result = null
            for (var i = 0, len = users.length; i < len; i++) {
                var user = users[i]
                if (user.name == name) {
                    result = user
                    break
                }
            }
            callback(null, result)
        })
    },
    findById: function(id, callback) {
        getData(function(err, users) {
            if (err) {
                callback(err)
                return
            }
            var result = null
            for (var i = 0, len = users.length; i < len; i++) {
                var user = users[i]
                if (user.id == id) {
                    result = user
                    break
                }
            }
            callback(null, result, users)

        })
    },
    //  未完
    findByIdAndUpdate: function(id, update, callback) {
        var handlerType = update.handlerType
        var content = update.content
        var status = 1; // 1 更新  2 未更新
        this.findById(id, function(err, user, users) {
            if (err) {
                callback(err)
            } else {
                switch (handlerType) {
                    case 'addCollect':
                        if (existsId(user, 'collectPost', content.postId)) {
                            callback('已经收藏过啦')
                        } else {
                            user.collectPost.push(content.postId)
                        }

                        break
                    case 'removeCollect':

                        user.collectPost = user.collectPost.filter(function(pid) {
                            return pid != content.postId
                        })
                        break
                    case 'addFans':
                        user.fans.push(content.userId)
                        break
                    case 'removeFans':
                        user.fans = user.fans.filter(function(uid) {
                            return uid != content.userId
                        })
                        break
                    case 'addCare':
                        if (existsId(user, 'care', content.userId)) {
                            callback('已经关注过啦')
                        } else {
                            user.care.push(content.userId)
                        }
                        break
                    case 'removeCare':
                        user.care = user.care.filter(function(uid) {
                            return uid != content.userId
                        })
                        break
                    default:
                        Object.assign(user, content)

                }

                var data = JSON.stringify(users, null, 4)

                setData(data, user, function(err, user) {
                    if (err) {
                        callback(err)
                    } else {
                        callback(null, user)
                    }
                })

            }
        })
    },
    insert: function(userInfo, callback) {
        getData(function(err, users) {
            if (err) {
                console.log('userHandler insert fail. err = ' + err)
                callback(err)
            } else {
                var newUser = util.createUserDb(userInfo)
                users.push(newUser)
                setData(JSON.stringify(users, null, 4), newUser, callback)
            }

        })
    },
    remove: function(filter, callback) {

        getData(function(err, users) {
            if (err) {
                console.log('userHandler remove fail. err = ' + err)
                callback('获取用户列表失败')
            } else {
                users = users.filter(function(user) {
                    for (var key in filter) {
                        if (user[key] == filter[key]) {
                            return false
                        }
                    }
                    return true
                })
                var data = JSON.stringify(users, null, 4)
                fs.writeFile(userPath + fileName, data, function(err) {
                    if (err) {
                        console.log('userHandler remove fail. err = ' + err)
                        callback('删除用户失败')
                    } else {
                        callback(null)
                    }
                })
            }
        })

    }
}


//  获取用户数据
function getData(callback) {
    safePathCheck(userPath, fileName, function(exists) {
        if (!exists) {
            console.log('用户数据路径出错')
            callback(null, [])
        } else {
            var data = fs.readFileSync(userPath + fileName)
            if (!data.length) {
                data = []
            } else {
                data = JSON.parse(data)
            }
            callback(null, data)
        }
    })
}

//  设置用户数据
function setData(data, newUser, callback) {
    safePathCheck(userPath, function(exists) {
        if (!exists) {
            console.log('用户数据路径出错')
            callback(null, [])
        } else {
            fs.writeFile(userPath + fileName, data, function(err) {
                if (err) {
                    console.log('userHandler setData fail. err = ' + err)
                    callback('注册用户失败')
                } else {
                    callback(null, newUser)
                }
            })
        }
    })
}

//  检查id是否存在于数组

function existsId(user, prop, id) {
    var arr = user[prop]
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == id) {
            return true
        }
    }
    return false
}